import 'package:flutter/material.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:xview/components/xTabSwiper/Tabs.dart';
import 'package:xview/utils/dimension.dart';

class XTabSwiper extends StatefulWidget {
  List<Map<String, dynamic>> list;
  String tabStartColor;
  String tabEndColor;
  Widget Function(BuildContext, int) itemBuilder;

  XTabSwiper({
    required this.list,
    this.tabStartColor = '#303133',
    this.tabEndColor = '#1661FF',
    required this.itemBuilder,
  });

  @override
  State<StatefulWidget> createState() {
    return _XTabSwiperState();
  }
}

class _XTabSwiperState extends State<XTabSwiper> {
  double dx = 0;
  SwiperController _controller = new SwiperController();

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      child: Column(
        children: [
          Tabs(
            dx: dx,
            list: widget.list,
            startColor: widget.tabStartColor,
            endColor: widget.tabEndColor,
            onClick: (idx){
              _controller.move(idx);
            },
          ),
          Expanded(
            child: Container(
              width: Dimension(context).toVw(100),
              child: NotificationListener<ScrollNotification>(
                onNotification: (ScrollNotification notification){
                  // 监听滑动过程
                  ScrollMetrics metrics = notification.metrics;
                  setState(() {
                    if(metrics.axis == Axis.horizontal){
                      dx = metrics.pixels;
                    }
                  });
                  // print('${metrics.pixels},${metrics.axis}');
                  return true;
                },
                child: NotificationListener<ScrollEndNotification>(
                  onNotification: (endNotification){
                    // 监听滑动结束
                    return false;
                  },
                  child: Swiper(
                    itemCount: widget.list.length,
                    controller: _controller,
                    loop: false,
                    autoplay: false,
                    scrollDirection: Axis.horizontal,
                    onTap:(index){
                      print(index);
                    },
                    itemBuilder: widget.itemBuilder,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
